﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace Sendz.Validators
{
    public class RegExRemoteValidator : DataAnnotationsModelValidator<RegExRemoteAttribute>
    {
        public RegExRemoteValidator(ModelMetadata metadata, ControllerContext context, RegExRemoteAttribute attribute)
            : base(metadata, context, attribute) { }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // Get a reference to the properties this validation depends upon
            var fieldRegEx = Metadata.ContainerType.GetProperty(Attribute.RegExProperty);

            if (fieldRegEx != null)
            {
                // Get the value of the dependent properties
                var valueRegEx = fieldRegEx.GetValue(container, null);

                // Ensure the values aren't null
                if (valueRegEx != null)
                {
                    // Ensure the values aren't blank or whitespace
                    if (!string.IsNullOrWhiteSpace(valueRegEx.ToString()))
                    {
                        var rxMatch = new Regex(valueRegEx.ToString());
                        if (Metadata.Model != null)
                        {
                            // Sometimes an array will be used since the ViewModel may capture multiple-item values in an array, so check for that
                            var thisVal = (Metadata.Model.GetType().ToString() == "System.String[]") ? string.Join(string.Empty, ((string[])Metadata.Model)) : (string)Metadata.Model;
        
                            if (!rxMatch.IsMatch(thisVal))
                                // Validation failed - return an error
                                yield return new ModelValidationResult { Message = ErrorMessage };
                        }
                    }
                }
            }
        }
        // No client-side needed with MVC Roundtrip validation! :)
    }
}
